import requests
from lxml import etree
from PIL import Image
from io import BytesIO
import sys

class Req:
    def __init__(self):
        print("init")

    def run(self):
        base_url = "https://ibaotu.com/sucai/483585.html"
        headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36","Cookie":"md_session_id=20191120001671799; user_refers=a%3A2%3A%7Bi%3A0%3Bs%3A7%3A%22comment%22%3Bi%3A1%3Bs%3A56%3A%22https%3A%2F%2Fblog.csdn.net%2Fliujiayu2%2Farticle%2Fdetails%2F86016531%22%3B%7D; _uab_collina=157423200531463345036117; islogout=1; Hm_lvt_2b0a2664b82723809b19b4de393dde93=1574232006; Hm_lvt_4df399c02bb6b34a5681f739d57787ee=1574232007; FIRSTVISITED=1574232007.424; bt_guid=5bf264a6a79f7465d81535cca49e6d64; Hm_lpvt_2b0a2664b82723809b19b4de393dde93=1574232030; Hm_lpvt_4df399c02bb6b34a5681f739d57787ee=1574232031; referer=http%3A%2F%2Fibaotu.com%2F%3Fm%3Dstats%26callback%3DjQuery191035262726922685417_1574232029995%26lx%3D3%26pagelx%3D13%26exectime%3D0.0132%26loadtime%3D0.655%26_%3D1574232029997"}
        payload = {"kwd": "双十二"}
        response = requests.get(base_url, params=payload,headers=headers)
        html = etree.HTML(response.text)
        url = "https:"+html.xpath("//a[@class='video-src']/@src")[0]
        # stream 原始套接字响应内容
        url = 'https://pic.ibaotu.com/00/51/34/88a888piCbRB.mp4'
        r = requests.get(url,stream=True)
        temp_size = 0
        # 文件总大小
        total_size = int(r.headers.get("Content-Length"))
        print('[文件大小]:%0.2f MB' % (total_size / 1024 / 1024))  # 换算单位并打印
        with open("test.mp4","wb") as mp4:
            for chunk in r.iter_content(chunk_size=1024 * 1024):
                if chunk:
                    mp4.write(chunk)
                    temp_size += len(chunk)
                    done = int(50 * temp_size / total_size)
                    sys.stdout.write("\r[%s%s] %d%%" % ('█' * done, ' ' * (50 - done), 100 * temp_size / total_size))
                    sys.stdout.flush()
if __name__ == "main":
    print("--main--")

req = Req()
req.run()
